<?php

include '../../../Smarty/Smarty.php';

class crazy_answer_second_activity extends controller{
    private $component_id = 41;
    private $question_level = array(
                                1=>'房务部',
                                2=>'餐饮部',
                                3=>'财务部',
                                4=>'市场营销部',
                                5=>'人力资源部',
                                6=>'工程部',
                                7=>'安保部',
                            );
//    public function __construct(){
//        $this->cache_time=0;
//        $this->caching = false;
//
//        $this->userInfo = $this->event();
//        if(isset($this->userInfo['code'])) {
//           $this->redirect();
//        }
//
//        $this->assign(array(
//                'signPackage'=>$this->getJsConfigData(),
//                'v' => time()
//            )
//        );
//    }
    
    //活动首页
    public function index(){
        //$openid = $this->userInfo['openid'];
        $openid = 'qKMHmjnOYKl34rx3RzvoUFOd_ETa';
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        $count = $CrazyAnswerSecondUser->compare('openid', $openid)->count();
        if(!$count){//新用户
            $CrazyAnswerSecondUser->openid = $openid;
            $CrazyAnswerSecondUser->meta = 'test';//微信用户信息
            //剩余关卡答题信息
            $level = array();
            for($i=1;$i<8;$i++){
                $level[$i] = 1;
            }
            $CrazyAnswerSecondUser->remaining_level = serialize($level);
            $CrazyAnswerSecondUser->add_time = Date('Y-m-d H:i:s');//添加时间
            if(!$CrazyAnswerSecondUser->save()){
                $this->showError('用户信息保存失败！');
            }
        }
        $data = $CrazyAnswerSecondUser->find('openid = "'.$openid.'"');
        
        $this->_addVisitLog('index');
        $this->assign('user_id',$data['id']);
        $this->display('index.html');
    }
    
    //关卡选择页
    public function remainingLevel(){
        $id = Yii::app()->request->getQuery('id');//用户id
        //获取关卡剩余信息
        $user_info = $this->getUserInfo($id);
        $level = unserialize(stripslashes($user_info['remaining_level']));//转化关卡序列化信息
        foreach($level as $k=>$v){
            $data[$k]['level'] = $level[$k];
            $data[$k]['question_level'] = $this->question_level[$k];
        }

        $this->_addVisitLog('page2');
        $this->assign('user_id', $id);
        $this->assign('data', $data);
        $this->display('page2.html');
    }
    
    //题目信息
    public function question(){
        $question_id = Yii::app()->request->getQuery('question_id');//关卡id
        $id = Yii::app()->request->getQuery('id');//用户id
        
        $user_info = $this->getUserInfo($id);
        $level = unserialize(stripslashes($user_info['remaining_level']));//转化剩余关卡抽奖序列化信息
        $draw = (int)$level[$question_id];//剩余答题机会
        //获取关卡名称
        $question_level = $this->question_level;
        $question_name = $question_level[$question_id];
        if($draw>0){
            $CrazyAnswerSecondQuestion = new CrazyAnswerSecondQuestion();
            //获取前半部分题目
            $criteria_f = new CDbCriteria();
            $criteria_f->addCondition('type = 1 and question_id = '.$question_id);
            $question_f = $CrazyAnswerSecondQuestion->queryAll($criteria_f);

            //获取后半部分题题目
            $criteria_a = new CDbCriteria();
            $criteria_a->addCondition('type = 2 and question_id = '.$question_id);
            $question_a = $CrazyAnswerSecondQuestion->queryAll($criteria_a);

            $num = count($question_f);//半部分的题目个数
            //n个数里面随机取5个
            $numbers = range (0,$num-1);
            shuffle($numbers);
            $result = array_slice($numbers,0,5);
            foreach($result as $k=>$v){
                $question_f[$v]['question_options'] = unserialize(stripslashes($question_f[$v]['question_options']));//将答案选项反序列化
                $questions_f[$k] = $question_f[$v];
                $question_a[$v]['question_options'] = unserialize(stripslashes($question_a[$v]['question_options']));//将答案选项反序列化
                $questions_a[$k] = $question_a[$v];
            }
            $question = array_merge($questions_f,$questions_a);//将前5题和后5题合并
            foreach($question as $key=>$val){
                $questions[$key+1] = $val;
            }

            $this->assign('questions',$questions);
            $this->assign('question_name',$question_name);
            $this->assign('question_id',$question_id);
            $this->assign('user_id', $id);
            $this->display('page3.html');
        }else{
            $this->assign('user_id', $id);
            $this->assign('question_name',$question_name);
            $this->display('end.html');
        }
    }
    
    //闯关成功页面
    public function enterSuccessfully(){
        $id = Yii::app()->request->getQuery('id');//用户id
        $time = Yii::app()->request->getQuery('time');//答题时间
        $question_id = Yii::app()->request->getQuery('question_id');//关卡id
        
        $time = substr($time, 0, -1);
        //记录答题最短用时
        $userinfo = $this->getUserInfo($id);
        if($userinfo['the_shortest_time'] == 0 || $userinfo['the_shortest_time'] > $time){
            $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
            $data['the_shortest_time'] = $time;
            $CrazyAnswerSecondUser->updateAll($data, 'id = '.$id);
        }
        //根据时间给予称号
        if($time <= 150){
            $title = '学霸';
        }else if($time > 150 && $time <= 250){
            $title = '学神';
        }else if($time > 250 && $time <= 350){
            $title = '学民';
        }else{
            $title = '学渣';
        }
        
        //目前排名
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        $criteria = new CDbCriteria();
        $criteria->select = 'id,the_shortest_time,meta';
        $criteria->addCondition('the_shortest_time <> 0');
        $criteria->order = 'the_shortest_time ASC, id ASC' ; 
        $list = $CrazyAnswerSecondUser->queryAll($criteria);
        foreach($list as $k=>$v){
            if($v['id'] == $id){
                $current_ranking = $k+1;
                break;
            }
        }
        
        $this->assign('time',$time);
        $this->assign('title',$title);
        $this->assign('question_id',$question_id);
        $this->assign('current_ranking',$current_ranking);
        $this->assign('user_id',$id);
        $this->display('page4.html');
    }
    
    /**
     * 我的奖品接口
     * @param int $id 用户id
    */
    public function myPrize(){
        $id = Yii::app()->request->getQuery('id');
        $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
        $criteria = new CDbCriteria();
        $criteria->addCondition('user_id = '.$id);
        $criteria->order = 'add_time DESC';
        $data = $CrazyAnswerSecondAwardLog->queryAll($criteria);
        empty($data) ? $this->ajaxTip(0,'无数据') : FALSE;
        $question_level = $this->question_level;
        //组装奖品名称
        foreach($data as $k=>$v){
            $arr = explode('-',$v['award_type']);
            if($arr[1] == 1){
                if($arr[0] != 0){
                    $data[$k]['prize_title'] = $question_level[$arr[0]].$arr[2];
                    $data[$k]['prize_name'] = '精品课程';
                }else{
                    $data[$k]['prize_title'] = '分享既得';
                    $data[$k]['prize_name'] = '通用课程';
                }
            }else if($arr[1] == 2){
                $data[$k]['prize_title'] = '分享既得';
                $data[$k]['prize_name'] = '通用课程';
            }
        }
        $this->ajaxTip(1,$data);
    }
    
    /**
     * 排行榜TOP5接口
    */
    public function rankingList(){
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        $criteria = new CDbCriteria();
        $criteria->select = 's.the_shortest_time,t.tel';
        $criteria->join = 'LEFT JOIN '.CrazyAnswerSecondUser::model()->tableName().' s ON t.user_id = s.id';
        $criteria->addCondition('s.the_shortest_time <> 0');
        $criteria->order = 's.the_shortest_time ASC, s.id ASC' ; 
        $criteria->limit = 5;
        $list = $CrazyAnswerSecondEnter->queryAll($criteria);
        foreach($list as $k=>$v){
            $list[$k]['tel'] = substr($v['tel'], 0, 3).'****'.substr($v['tel'], -4, 4);
        }
        
        empty($list) ? $this->ajaxTip(0,'无数据！') : $this->ajaxTip(1,$list);
    }
    
    /**
     * 更改关卡剩余信息接口
     * @param int $id 用户id
     * @param int $question_id 关卡id
    */
    public function changeLevelSurplus(){
        $id = Yii::app()->request->getQuery('id');
        $question_id = Yii::app()->request->getQuery('question_id');
        $userInfo = $this->getUserInfo($id);
        $arr = unserialize($userInfo['remaining_level']);
        $arr[$question_id] = 0;
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        $data['remaining_level'] = serialize($arr);
        $res = $CrazyAnswerSecondUser->updateAll($data, 'id = '.$id);
        $res ? $this->ajaxTip(1,$res) : $this->ajaxTip(0,'答题机会更改失败！');
    }
    
    /**
     * 检测是否填写过报名信息接口
     * @param int $id 用户id
     * @param int $award_type 奖项类型：关卡id-获奖类型(1:学神以上称号，2:分享)-称号
    */
    public function checkEnter(){
        $user_id = Yii::app()->request->getQuery('id');
        $award_type = Yii::app()->request->getQuery('award_type');
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        $res = $CrazyAnswerSecondEnter->find('user_id = '.$user_id);
        if($res){//存在报名信息
            $status = $this->saveAwardLog($user_id, $award_type);
            $status ? $this->ajaxTip(1,$status) : $this->ajaxTip(0,'奖励记录保存失败！');
        }else{
            $this->ajaxTip(2,'不存在报名信息！');
        }
    }
    
    /**
     * 保存奖励记录信息和报名信息接口
     * @param int $id 用户id
     * @param int $name 用户姓名
     * @param int $tel 手机号
     * @param int $award_type 奖项类型：关卡id-获奖类型(1:学神以上称号，2:分享)-称号
    */
    public function saveAwardEnter(){
        $user_id = Yii::app()->request->getQuery('id');
        $name = Yii::app()->request->getQuery('name');
        $tel = Yii::app()->request->getQuery('tel');
        $award_type = Yii::app()->request->getQuery('award_type');
        $CrazyAnswerSecondEnter = new CrazyAnswerSecondEnter();
        $CrazyAnswerSecondEnter->user_id = $user_id;
        $CrazyAnswerSecondEnter->name = $name;
        $CrazyAnswerSecondEnter->tel = $tel;
        $CrazyAnswerSecondEnter->add_time = Date('Y-m-d H:i:s');
        if($CrazyAnswerSecondEnter->save()){
            $status = $this->saveAwardLog($user_id, $award_type);
            $status ? $this->ajaxTip(1,$status) : $this->ajaxTip(0,'奖励记录保存失败！');
        }else{
            $this->ajaxTip(0,'保存报名信息失败！');
        }
    }
    
    /**
     * 更改领取状态接口
     * @param int $id 用户id
     * @param int $draw_status 闯关成功领取状态 0-已领取，1-未领取
    */
    public function changeDrawStatus(){
        $user_id = Yii::app()->request->getQuery('id');
        $draw_status = Yii::app()->request->getQuery('draw_status');
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        //判断闯关成功领取状态已经为1的话，则不做处理
        if($draw_status == 1){
            $da = $CrazyAnswerSecondUser->find('id = '.$user_id);
            $da['draw_status'] == 1 ? $this->ajaxTip(1,'') : FALSE;
        }
        $data['draw_status'] = $draw_status;
        $res = $CrazyAnswerSecondUser->updateAll($data, 'id = '.$user_id);
        $res ? $this->ajaxTip(1,'更改成功！') : $this->ajaxTip(0,'更改失败！');
    }
    
    /**
     * 获取闯关成功后的领取状态接口
     * @param int $id 用户id
     * @param int $draw_status 闯关成功领取状态 0-已领取，1-未领取
    */
    public function getDrawStatus(){
        $user_id = Yii::app()->request->getQuery('id');
        $data = $this->getUserInfo($user_id);
        $this->ajaxTip($data['draw_status'],'');
    }

    /**
     * 检测是否已分享领取过奖励接口
     * @param int $id 用户id
    */
    public function checkShare(){
        $id = Yii::app()->request->getQuery('id');
        $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
        $criteria = new CDbCriteria();
        $criteria->addCondition('user_id = '.$id);
        $data = $CrazyAnswerSecondAwardLog->queryAll($criteria);
        if(empty($data)){//无数据，则为未领取
            $this->ajaxTip(0,'未领取');
        }else{
            //循环判断是否存在分享记录
            foreach($data as $k=>$v){
                $arr = explode('-',$v['award_type']);
                if($arr[1] == 2){
                    $this->ajaxTip(1,'已领取');
                    break;
                }
            }
            $this->ajaxTip(0,'未领取');
        }
    }
    
    /**
     * 获取用户信息
     * @param int $id 用户id
     * @return array
    */
    private function getUserInfo($id){
        $CrazyAnswerSecondUser = new CrazyAnswerSecondUser();
        $data = $CrazyAnswerSecondUser->find('id = '.$id);
        return $data;
    }
    
    /**
     * 保存奖励记录信息
     * @param int $id 用户id
     * @param int $award_type 奖项类型：关卡id-获奖类型(1:学神以上称号，2:分享)-称号
     * @return int
    */
    private function saveAwardLog($id, $award_type){
        $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
        $CrazyAnswerSecondAwardLog->user_id = $id;
        $CrazyAnswerSecondAwardLog->award_type = $award_type;
        $CrazyAnswerSecondAwardLog->add_time = Date('Y-m-d H:i:s');
        if($CrazyAnswerSecondAwardLog->save()){
            return TRUE;
        }else{
            return FALSE;
        }
    }
    
    /**
     * js分享成功回调，统计页面分享数据
     */
    public function shareSuccess(){
	$title = Yii::app()->getRequest()->getParam('title',0);
	$content = Yii::app()->getRequest()->getParam('content',0);
	$type = Yii::app()->getRequest()->getParam('type',0);
	if(!empty($title) && !empty($content) && !empty($content)){
            $XzShare_new = new XzShare_new();
            $XzShare_new->openid = $this->userInfo['openid'];
            $XzShare_new->component_id = $this->component_id;
            $XzShare_new->title = $title;
            $XzShare_new->content = $content;
            $XzShare_new->type = $type;
            $XzShare_new->date = date('Y-m-d');
            $XzShare_new->add_time = date('Y-m-d H:i:d');
            $XzShare_new->save();
        }
    }
    
    /**
     * 统计页面访问量
     * @param string $name
     */
    private function _addVisitLog($name){
        $ContestStatistic_new = new ContestStatistic_new();
        //$ContestStatistic_new->openid = $this->userInfo['openid'];
        $ContestStatistic_new->openid = 'oKMHmjnOYKl34rx3RzvoUFOd_ETQ';
        $ContestStatistic_new->component_id = $this->component_id;
        $ContestStatistic_new->page = $name;
        $ContestStatistic_new->add_time = time();
        $ContestStatistic_new->save();
    }
    
    /**
     * 统计按钮点击数
     * @param string $name
     */
    public function _addButtonLog(){
        $name = Yii::app()->request->getQuery('name');
        $ContestButton = new ContestButton();
        //$ContestButton->openid = $this->userInfo['openid'];
        $ContestButton->openid = 'oKMHmjnOYKl34rx3RzvoUFOd_ETQ';
        $ContestButton->component_id = $this->component_id;
        $ContestButton->button = $name;
        $ContestButton->add_time = time();
        $ContestButton->save();
    }
    

    //创建题目页面
    public function createQuestion(){
        //$this->display('page3.html');
        //获取所有关卡信息
        $data = $this->question_level;

        $this->assign('data',$data);
        $this->display('create_question.html');
    }
    
    //保存题目
    public function saveQuestion(){
        header("Content-type: text/html; charset=utf-8"); 
        
        if($_POST){
            $criteria = new CrazyAnswerSecondQuestion();
            
            //获取题目答案选项
            empty(Yii::app()->request->getPost('question_a')) ? FALSE : $questions['A'] = Yii::app()->request->getPost('question_a');
            empty(Yii::app()->request->getPost('question_b')) ? FALSE : $questions['B'] = Yii::app()->request->getPost('question_b');
            empty(Yii::app()->request->getPost('question_c')) ? FALSE : $questions['C'] = Yii::app()->request->getPost('question_c');
            empty(Yii::app()->request->getPost('question_d')) ? FALSE : $questions['D'] = Yii::app()->request->getPost('question_d');
            $criteria->question_options = serialize($questions);//答案选项
            $criteria->question_id = Yii::app()->request->getPost('question_id');//关卡id
            $criteria->question = Yii::app()->request->getPost('question');//问题
            $criteria->answer = Yii::app()->request->getPost('answer');//正确答案
            $criteria->answer_key = Yii::app()->request->getPost('answer_key');//答案解析
            $criteria->type = Yii::app()->request->getPost('type');//答案解析
            $criteria->add_time = Date('Y-m-d H:i:s');//添加时间
            
            if($criteria->save()){
                $url = './index.php?a=createQuestion';
                header("Location:" . $url);
            }else{
                echo '添加失败';
            }
        }
    }
    
    public function test(){
            header("Content-type: text/html; charset=utf-8"); 
            //$usql = "truncate table wams_crazy_answer_second_enter";
        //$usql = "truncate table wams_crazy_answer_enter";
        //$usql = "truncate table wams_crazy_answer_prize_log";
        //$usql = "delete from wams_contest_statistic where component_id=40";
        //$usql = "delete from wams_xz_share where component_id=40";
        
        //CrazyAnswerSecondUser::model()->getDbConnection()->createCommand($usql)->execute();
            $CrazyAnswerSecondAwardLog = new CrazyAnswerSecondAwardLog();
            $data = $CrazyAnswerSecondAwardLog->queryAll();
            var_dump($data);
    }
    
    
    

}

$crazy_answer_second_activity = new crazy_answer_second_activity;

$action = isset($_GET['a']) ? trim($_GET['a']) : 'index';

$crazy_answer_second_activity->$action();